/**
 * Created by MorenYang on 2017/11/10.
 */

const AUTH_USER_FLAG = 'USER',
  AUTH_TOKEN_FLAG = 'TOKEN';

const auth = (state = getAuthState(), action) => {
  switch (action.type) {
    case 'USER_LOGIN' : {
      const {user, token} = action;
      setAuthState({user, token});
      return {user, token};
    }
    case 'SET_USER': {
      const {user} = action;
      setUser({user});
      return getAuthState();
    }
    case 'USER_LOGOUT':
      clearAuthState();
      return getAuthState();
    default:
      return state
  }
};

export default auth;

const getAuthState = () => {
  let user = null, token = null;
  if (!!localStorage.getItem(AUTH_TOKEN_FLAG)) {
    token = localStorage.getItem(AUTH_TOKEN_FLAG);
    //user =  JSON.parse(localStorage.getItem(AUTH_USER_FLAG));
      user = {};
  }
  return {user, token}
};

const setAuthState = ({user, token}) => {
  localStorage.setItem(AUTH_USER_FLAG, JSON.stringify(user));
  localStorage.setItem(AUTH_TOKEN_FLAG, token);
};

const setUser = ({user}) => {
  localStorage.setItem(AUTH_USER_FLAG, JSON.stringify(user))
};

const clearAuthState = () => {
  localStorage.removeItem(AUTH_TOKEN_FLAG);
  localStorage.removeItem(AUTH_USER_FLAG);
};
